<template>
	<view>
		<view class="wrap">
			<view class="u-tabs-box">
				<up-tabs activeColor="#f29100" ref="tabs" :list="list" :current="current" @change="change" :is-scroll="false" swiperWidth="750"></up-tabs>
			</view>
			<swiper class="swiper-box" :current="swiperCurrent" @animationfinish="animationfinish">
				<swiper-item class="swiper-item">
					<scroll-view scroll-y style="height: 100%; width: 100%" v-if="data.order.length !== 0">
						<view class="page-box" v-for="(res, index) in data.order" :key="res.id">
							<view class="order" v-if="res.status === '待支付'">
								<view class="top">
									<view class="left">店家名字</view>
									<view class="right">{{ res.status }}</view>
								</view>
								<view class="shopping-card" v-for="(item, index) in data.product" :key="index">
									<view class="" v-for="(subItem, subIndex) in item" :key="subIndex">
										<view class="item" v-if="res.order_id === subItem['order_id']">
											<view class="left"><image :src="subItem['product_image']" mode="aspectFill"></image></view>
											<view class="content">
												<view class="title u-line-2">{{ subItem['product_name'] }}</view>
												<view class="delivery-time">{{ subItem['product_description'] }}</view>
												<view class="right">
													<view class="price">￥{{ subItem['subtotal_price'] }}</view>
													<view class="number">x{{ subItem['quantity'] }}</view>
												</view>
											</view>
										</view>
									</view>
								</view>
								<view class="total">
									合计:
									<text class="total-price">￥{{ res.total_amount }}</text>
								</view>
								<view class="bottom">
									<view class="more"><up-icon name="more-dot-fill" color="rgb(203,203,203)"></up-icon></view>
									<view class="logistics btn">查看物流</view>
									<view class="exchange btn" @click="cancelPay(res)">取消支付</view>
									<view class="evaluate btn" @click="keepBuy(res)">继续购买</view>
								</view>
							</view>
						</view>
					</scroll-view>
					<scroll-view scroll-y style="height: 100%; width: 100%" v-else>
						<view class="page-box">
							<view>
								<view class="centre">
									<image src="https://cdn.uviewui.com/uview/template/taobao-order.png" mode=""></image>
									<view class="explain">
										您还没有相关的订单
										<view class="tips">可以去看看有那些想买的</view>
									</view>
									<view class="btn">随便逛逛</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
				<swiper-item class="swiper-item">
					<scroll-view scroll-y style="height: 100%; width: 100%" v-if="!!data.order.length">
						<view class="page-box" v-for="(res, index) in data.order" :key="res.id">
							<view class="order" v-if="res.status === '待发货'">
								<view class="top">
									<view class="left">{{ convertISOToCustomFormat(res.created_at) }}</view>
									<view class="right">{{ res.status }}</view>
								</view>
								<view class="shopping-card" v-for="(item, index) in data.product" :key="index">
									<view class="" v-for="(subItem, subIndex) in item" :key="subIndex">
										<view class="item" v-if="res.order_id === subItem['order_id']">
											<view class="left"><image :src="subItem['product_image']" mode="aspectFill"></image></view>
											<view class="content">
												<view class="title u-line-2">{{ subItem['product_name'] }}</view>
												<view class="delivery-time">{{ subItem['product_description'] }}</view>
												<view class="right">
													<view class="price">￥{{ subItem['subtotal_price'] }}</view>
													<view class="number">x{{ subItem['quantity'] }}</view>
												</view>
											</view>
										</view>
									</view>
								</view>
								<view class="total">
									合计:
									<text class="total-price">￥{{ res.total_amount }}</text>
								</view>
								<view class="bottom">
									<view class="more"><up-icon name="more-dot-fill" color="rgb(203,203,203)"></up-icon></view>
									<view class="logistics btn">查看物流</view>
									<view class="exchange btn" @click="cancelOrder(res)">取消订单</view>
									<view class="evaluate btn" @click="confirmOrder(res)">确认收货</view>
								</view>
							</view>
						</view>
					</scroll-view>
					<scroll-view scroll-y style="height: 100%; width: 100%" v-else>
						<view class="page-box">
							<view>
								<view class="centre">
									<image src="https://cdn.uviewui.com/uview/template/taobao-order.png" mode=""></image>
									<view class="explain">
										您还没有相关的订单
										<view class="tips">可以去看看有那些想买的</view>
									</view>
									<view class="btn">随便逛逛</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
				<swiper-item class="swiper-item">
					<scroll-view scroll-y style="height: 100%; width: 100%">
						<view class="page-box">
							<view>
								<view class="centre">
									<image src="https://cdn.uviewui.com/uview/template/taobao-order.png" mode=""></image>
									<view class="explain">
										您还没有相关的订单
										<view class="tips">可以去看看有那些想买的</view>
									</view>
									<view class="btn">随便逛逛</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
				<swiper-item class="swiper-item">
					<scroll-view scroll-y style="height: 100%; width: 100%" v-if="!!data.order.length">
						<view class="page-box" v-for="(res, index) in data.order" :key="res.id">
							<view class="order" v-if="res.status == '已完成'||res.status =='已取消'">
								<view class="top">
									<view class="left">{{ convertISOToCustomFormat(res.created_at) }}</view>
									<view class="right">{{ res.status }}</view>
								</view>
								<view class="shopping-card" v-for="(item, index) in data.product" :key="index">
									<view class="" v-for="(subItem, subIndex) in item" :key="subIndex">
										<view class="item" v-if="res.order_id === subItem['order_id']">
											<view class="left"><image :src="subItem['product_image']" mode="aspectFill"></image></view>
											<view class="content">
												<view class="title u-line-2">{{ subItem['product_name'] }}</view>
												<view class="delivery-time">{{ subItem['product_description'] }}</view>
												<view class="right">
													<view class="price">￥{{ subItem['subtotal_price'] }}</view>
													<view class="number">x{{ subItem['quantity'] }}</view>
												</view>
											</view>
										</view>
									</view>
								</view>
								<view class="total">
									合计:
									<text class="total-price">￥{{ res.total_amount }}</text>
								</view>
								<view class="bottom">
									<view class="more"><up-icon name="more-dot-fill" color="rgb(203,203,203)"></up-icon></view>
									<view class="evaluate btn">评价</view>
								</view>
							</view>
						</view>
					</scroll-view>
					<scroll-view scroll-y style="height: 100%; width: 100%" v-else>
						<view class="page-box">
							<view>
								<view class="centre">
									<image src="https://cdn.uviewui.com/uview/template/taobao-order.png" mode=""></image>
									<view class="explain">
										您还没有相关的订单
										<view class="tips">可以去看看有那些想买的</view>
									</view>
									<view class="btn">随便逛逛</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>
<script setup>
import { ref, onMounted, reactive, watchEffect, watch,getCurrentInstance } from 'vue';
import { GetOrderFromId, GetOrderFromOrderId, ChangeOrderStatus, ChangeShoppingInventory, ChangeCancelShoppingInventory } from '../../apis/api.js';
import convertISOToCustomFormat from '../../utils/timeChange.js';


const list = ref([
	{
		name: '待支付'
	},
	{
		name: '待发货'
	},
	{
		name: '待收货'
	},
	{
		name: '已完成',
		count: 12
	}
]);
const current = ref(2);
const swiperCurrent = ref(2);

const data = reactive({
	user_id: '',
	order: '',
	total_amount: '',
	product: []
});

// tab栏切换
const change = (e) => {
	console.log(e);
	console.log(e.index);
	swiperCurrent.value = e.index;
	// getOrderList(e.index);
	console.log(swiperCurrent.value);
};


// 获取url地址参数
// 跳转页面获取地址信息
onMounted(()=>{
	 const instance = getCurrentInstance().proxy
	 console.log(instance.options);
	 current.value=instance.options.current
	 swiperCurrent.value=instance.options.swiperCurrent
})

// 滑动轮播图，上面的tab切换
const animationfinish = (e) => {
	// console.log(e.detail)
	swiperCurrent.value = e.detail.current;
	current.value = e.detail.current;
};

// 获取用户的订单
watchEffect(() => {
	uni.getStorage({
		key: 'userId',
		success: async (res) => {
			data.user_id = res.data;
			console.log('获取的 userId 为：', data.user_id);
			watchEffect(() => {
				GetOrderFromId({
					user_id: data.user_id
				}).then((res) => {
					console.log(res);
					if (res.msgType == 8000) {
						data.order = res.data;
						console.log(data.order);
						// 通过order_id查看具体的商品
						data.order.forEach((item) => {
							console.log(item);
							console.log(item.order_id);
							GetOrderFromOrderId({
								order_id: item.order_id
							}).then((res) => {
								if (res.msgType == 8000) {
									data.product.push(res.data);
									console.log(res);
								}
							});
						});
					}
				});
			});
		},
		fail: (error) => {
			console.error('获取 userId 失败：', error);
		}
	});
});

// 继续购买，更换待支付为待收货
const keepBuy = (e) => {
	console.log(e);
	console.log(e.order_id);
	// ChangeOrderStatus
	watch(() => {
		uni.showModal({
			title: '确认购买',
			content: '确定要购买商品吗？',
			success: function (res) {
				if (res.confirm) {
					console.log(e.order_id);

					// 确认提交购买
					ChangeOrderStatus({
						status: '待发货',
						order_id: e.order_id
					}).then((res) => {
						if (res.msgType == 8000) {
							GetOrderFromOrderId({
								order_id: e.order_id
							}).then((res) => {
								// console.log(res);
								res.data.forEach((item) => {
									ChangeShoppingInventory({
										inventory: item.quantity,
										product_id: item.product_id
									});
								});
							});
							uni.redirectTo({
								url: '/pages/payment/payment?pay=' + e.total_amount
							});
							GetOrderFromId({
								user_id: data.user_id
							});
						}
					});
				} else {
					console.log(e);
				}
			}
		});
	});
};

// 确认收货
const confirmOrder = async (e) => {
	console.log(e);
	console.log(e.order_id);

	try {
		const res = await uni.showModal({
			title: '确认收货',
			content: '确定收货吗？'
		});

		if (res.confirm) {
			console.log(e.order_id);

			// 修改订单状态为'已完成'
			const statusRes = await ChangeOrderStatus({
				status: '已完成',
				order_id: e.order_id
			});

			if (statusRes.msgType == 8000) {
				// 如果状态修改成功，重新获取订单数据
				const orderRes = await GetOrderFromId({
					user_id: data.user_id
				});

				if (orderRes.msgType == 8000) {
					// 更新订单数据
					data.order = orderRes.data;
					// 显示提示或其他反馈
					uni.showToast({
						title: '确认收货成功',
						icon: 'none'
					});
				}
			} else {
				uni.showToast({
					title: '确认收货失败，请稍后再试',
					icon: 'none'
				});
			}
		} else {
			console.log(e);
		}
	} catch (error) {
		console.error('错误：', error);
	}
};

// 取消订单
const cancelOrder = async (e) => {
	console.log(e);
	console.log(e.order_id);
	// data.product.forEach((item) => {
	// 	console.log(item);
	// });

	try {
		const res = await uni.showModal({
			title: '确认收货',
			content: '确定收货吗？'
		});

		if (res.confirm) {
			console.log(e.order_id);

			// 修改订单状态为'已完成'
			const statusRes = await ChangeOrderStatus({
				status: '已取消',
				order_id: e.order_id
			});

			if (statusRes.msgType == 8000) {
				
				// 取消订单，修改库存
				GetOrderFromOrderId({
					order_id: e.order_id
				}).then((res) => {
					if (res.msgType == 8000) {
						res.data.forEach((item) => {
							ChangeCancelShoppingInventory({
								inventory: item.quantity,
								product_id: item.product_id
							}).then((res) => {
								console.log(res);
							});
						});
					}
				});

				// 如果状态修改成功，重新获取订单数据
				const orderRes = await GetOrderFromId({
					user_id: data.user_id
				});
				if (orderRes.msgType == 8000) {
					// 更新订单数据
					data.order = orderRes.data;
					// 显示提示或其他反馈
					uni.showToast({
						title: '确认取消成功',
						icon: 'none'
					});
				}
			} else {
				uni.showToast({
					title: '确认取消失败，请稍后再试',
					icon: 'none'
				});
			}
		} else {
			console.log(e);
		}
	} catch (error) {
		console.error('错误：', error);
	}
};

// 取消支付
const cancelPay= async (e) => {
	console.log(e);
	console.log(e.order_id);

	try {
		const res = await uni.showModal({
			title: '确认取消支付',
			content: '确定取消支付吗？'
		});

		if (res.confirm) {
			console.log(e.order_id);

			// 修改订单状态为'已完成'
			const statusRes = await ChangeOrderStatus({
				status: '已取消',
				order_id: e.order_id
			});

			if (statusRes.msgType == 8000) {
				// 如果状态修改成功，重新获取订单数据
				const orderRes = await GetOrderFromId({
					user_id: data.user_id
				});

				if (orderRes.msgType == 8000) {
					// 更新订单数据
					data.order = orderRes.data;
					// 显示提示或其他反馈
					uni.showToast({
						title: '确认取消支付成功',
						icon: 'none'
					});
				}
			} else {
				uni.showToast({
					title: '确认取消支付成功失败，请稍后再试',
					icon: 'none'
				});
			}
		} else {
			console.log(e);
		}
	} catch (error) {
		console.error('错误：', error);
	}
};
</script>

<style lang="less" scoped>
.wrap {
	// display: flex;
	// flex-direction: column;
	height: 100vh;
	width: 100%;
}
.swiper-box {
	height: 100%;
	.order {
		width: 710rpx;
		background-color: #ffffff;
		margin: 20rpx auto;
		border-radius: 20rpx;
		box-sizing: border-box;
		padding: 20rpx;
		font-size: 28rpx;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
		.top {
			display: flex;
			justify-content: space-between;
			.left {
				display: flex;
				align-items: center;
				.store {
					margin: 0 10rpx;
					font-size: 32rpx;
					font-weight: bold;
				}
			}
			.right {
				color: #f29100;
			}
		}
		.item {
			display: flex;
			margin: 20rpx 0 0;
			.left {
				margin-right: 20rpx;
				image {
					width: 200rpx;
					height: 200rpx;
					border-radius: 10rpx;
				}
			}
			.content {
				width: 100%;
				.title {
					font-size: 28rpx;
					line-height: 50rpx;
				}
				.type {
					margin: 10rpx 0;
					font-size: 24rpx;
					// color: $u-tips-color;
				}
				.delivery-time {
					color: #000000;
					font-size: 24rpx;
				}
			}
			.right {
				display: flex;
				justify-content: space-between;
				margin-left: 10rpx;
				padding-top: 20rpx;
				text-align: center;
				.decimal {
					font-size: 24rpx;
					margin-top: 4rpx;
				}
				.number {
					color: #c6c6c6;
					font-size: 24rpx;
				}
			}
		}
		.total {
			margin-top: 20rpx;
			text-align: right;
			font-size: 24rpx;
			.total-price {
				font-size: 32rpx;
			}
		}
		.bottom {
			display: flex;
			margin-top: 40rpx;
			padding: 0 10rpx;
			justify-content: space-between;
			align-items: center;
			.btn {
				line-height: 52rpx;
				width: 160rpx;
				border-radius: 26rpx;
				border: 2rpx solid tray;
				font-size: 26rpx;
				text-align: center;
				color: #f29100;
			}
			.evaluate {
				color: #f29100;
				border-color: #ffffff;
			}
		}
	}
}
.swiper-item {
	height: 100%;
	.centre {
		text-align: center;
		margin: 200rpx auto;
		font-size: 32rpx;
		image {
			width: 164rpx;
			height: 164rpx;
			border-radius: 50%;
			margin-bottom: 20rpx;
		}
		.tips {
			font-size: 24rpx;
			color: #999999;
			margin-top: 20rpx;
		}
		.btn {
			margin: 80rpx auto;
			width: 200rpx;
			border-radius: 32rpx;
			line-height: 64rpx;
			color: #ffffff;
			font-size: 26rpx;
			background: linear-gradient(270deg, rgba(249, 116, 90, 1) 0%, rgba(255, 158, 1, 1) 100%);
		}
	}
}
</style>
